import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/core/utils/wifi/wifi_utils.dart';
import 'package:casdon/modules/device/ui/widgets/device_pairnet_list_Item.dart';
import 'package:casdon/modules/device/ui/screen/wifi_config_screen.dart';
import 'package:casdon/modules/device/application/notification/device_discovery_provider.dart';
import 'package:casdon/modules/device/application/notification/pair_net_notifier.dart';
import 'package:casdon/modules/device/domain/states/pair_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

@RoutePage()
class PairnetListScreen extends ConsumerStatefulWidget {
  final String? ssid;
  final String? pwd;
  const PairnetListScreen({super.key, this.ssid, this.pwd});

  @override
  ConsumerState<PairnetListScreen> createState() => _PairnetListScreenState();
}

class _PairnetListScreenState extends ConsumerState<PairnetListScreen>
    with TickerProviderStateMixin {
  final List<ThingSmartDeviceModel> _realtimeDevices = [];
  StreamSubscription<ThingSmartDeviceModel>? _subscription;

  late AnimationController _controller;
  String? _ssid;
  String? _pwd;
  String _normalizeUuid(String uuid) => uuid.toLowerCase();

  @override
  void initState() {
    super.initState();
    _ssid = widget.ssid;
    _pwd = widget.pwd;
    _startListening();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();
  }

  void _startListening() {
    final notifier = ref.read(deviceDiscoveryProvider.notifier);
    final state = ref.read(deviceDiscoveryProvider);
    _realtimeDevices.addAll(state.devices);
    _subscription = notifier.deviceStream.listen((device) {
      if (!mounted) return;
      setState(() {
        // 去重检查
        final target = _normalizeUuid(device.uuid);
        if (!_realtimeDevices.any((d) => _normalizeUuid(d.uuid) == target)) {
          _realtimeDevices.add(device);
        }
      });
    });
  }

  @override
  void dispose() {
    Log.i('♻️ 释放PairnetListScreen资源');
    _controller.dispose();
    _subscription?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isSearching = ref.watch(isSearchingProvider);
    final pairStates = ref.watch(pairNetProvider);

    // 检查是否有设备正在配网中
    final hasPairingInProgress = pairStates.any(
      (state) => state.state == PairState.process,
    );

    // 检查是否有设备配网成功
    final hasPairSuccess = pairStates.any(
      (state) => state.state == PairState.success,
    );

    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: CommonAppBar(
        title: '添加设备',
        onBack: () async {
          if (hasPairingInProgress) {
            await TuyaService().stopBleWifiConfig();
            // 使用原生的 showDialog 避免路由栈问题
            final result = await showCustomConfirmDialog(
              context: context,
              content: "设备添加中，确定退出添加？",
            );
            if (result == true && context.mounted) {
              // 等待弹窗完全关闭，确保路由栈状态恢复
              await Future.delayed(const Duration(milliseconds: 500));

              // 使用 addPostFrameCallback 确保在下一帧执行返回
              WidgetsBinding.instance.addPostFrameCallback((_) {
                if (context.mounted) {
                  context.router.maybePop();
                }
              });
            }
          } else {
            if (context.mounted) {
              context.router.maybePop();
            }
          }
        },
      ),
      body: Column(
        children: [
          isSearching
              ? _buildSearchingView(context, ref)
              : _buildSearchStopView(context, ref),
          SizedBox(height: 4.h),
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 72.h,
              ),
              itemCount: _realtimeDevices.length,
              itemBuilder: (_, index) => DevicePairnetListItem(
                device: _realtimeDevices[index],
                onIdleTap: (device) => _handleIdleTap(device),
                onFailedTap: (device, isWifiConfigError) =>
                    _handleFailedTap(device, isWifiConfigError),
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: _buildBottomActionBar(context, hasPairSuccess),
    );
  }

  Widget _buildSearchingView(BuildContext context, WidgetRef ref) {
    final controller = _controller;
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          Text(
            '正在搜索附近设备',
            style: TextStyle(
              fontSize: 14.r,
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
          SizedBox(width: 8.w),
          RotationTransition(
            turns: controller,
            child: Assets.images.icLoading.image(
              width: 20.w,
              height: 20.w,
              fit: BoxFit.contain,
            ),
          ),
          const Spacer(),
        ],
      ),
    );
  }

  Widget _buildSearchStopView(BuildContext context, WidgetRef ref) {
    final service = ref.read(deviceDiscoveryProvider.notifier);
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          Text(
            '搜索附近设备已暂停',
            style: TextStyle(
              fontSize: 14.r,
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
          SizedBox(width: 8.w),
          GestureDetector(
            onTap: () => service.discoverDevices(),
            child: RichText(
              text: TextSpan(
                style: context.textTheme.bodyMedium?.copyWith(
                  color: Colors.grey[600],
                ),
                children: [
                  TextSpan(
                    text: '重新搜索',
                    style: context.textTheme.bodyMedium?.copyWith(
                      color: context.colorScheme.primary,
                    ),
                  ),
                ],
              ),
            ),
          ),
          const Spacer(),
        ],
      ),
    );
  }

  Widget _buildBottomActionBar(BuildContext context, bool hasPairSuccess) {
    return Container(
      decoration: const BoxDecoration(color: Colors.transparent),
      child: SafeArea(
        top: false,
        bottom: true,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
          child: GradientButton(
            text: "完成",
            textStyle: context.textTheme.labelLarge?.copyWith(
              color: Colors.white,
            ),
            enabled: hasPairSuccess,
            borderRadius: 24,
            onPressed: () {
              if (!hasPairSuccess) return;
              // 回到应用首页
              context.router.popUntilRouteWithName(TabRoute.name);
            },
          ),
        ),
      ),
    );
  }

  Future<void> _handleIdleTap(ThingSmartDeviceModel device) async {
    final wifiInfo = await _checkWifiInfo();
    if (_ssid != null) {
      ref
          .read(pairNetProvider.notifier)
          .enqueueSinglePairings(
            devices: [device],
            ssid: wifiInfo.ssid!,
            password: wifiInfo.password!,
          );
      return;
    }

    if (wifiInfo.ssid != null && wifiInfo.password != null) {
      _ssid = wifiInfo.ssid;
      _pwd = wifiInfo.password;
      ref
          .read(pairNetProvider.notifier)
          .enqueueSinglePairings(
            devices: [device],
            ssid: wifiInfo.ssid!,
            password: wifiInfo.password!,
          );
      return;
    }

    final result = await _showModalWifiConfig(context);
    final ssid = result?['ssid']?.toString();
    final pwd = result?['pwd']?.toString();
    if (ssid != null && ssid.isNotEmpty && pwd != null && pwd.isNotEmpty) {
      setState(() {
        _ssid = ssid;
        _pwd = pwd;
      });
      ref
          .read(pairNetProvider.notifier)
          .enqueueSinglePairings(devices: [device], ssid: ssid, password: pwd);
    }
  }

  Future<void> _handleFailedTap(
    ThingSmartDeviceModel device,
    bool isWifiConfigError,
  ) async {
    if (isWifiConfigError) {
      final result = await _showModalWifiConfig(context);
      final ssid = result?['ssid']?.toString();
      final pwd = result?['pwd']?.toString();
      if (ssid != null && ssid.isNotEmpty && pwd != null && pwd.isNotEmpty) {
        setState(() {
          _ssid = ssid;
          _pwd = pwd;
        });
        ref
            .read(pairNetProvider.notifier)
            .enqueueSinglePairings(
              devices: [device],
              ssid: ssid,
              password: pwd,
            );
      }
      return;
    }

    final ssid = _ssid;
    final pwd = _pwd;
    if (ssid != null && pwd != null) {
      ref
          .read(pairNetProvider.notifier)
          .enqueueSinglePairings(devices: [device], ssid: ssid, password: pwd);
      return;
    }
    // _handleFailedTap 的最后一行 await _handleIdleTap(device); 是一个兜底：
    // 当设备处于失败状态且没有已缓存的 _ssid/_pwd
    await _handleIdleTap(device);
  }

  Future<({String? ssid, String? password})> _checkWifiInfo() async {
    final ssidResult =
        await WifiUtils.getInstance().getCurrentWifiSsidResult();
    if (!ssidResult.hasPermission) {
      ToastUtil.show("请开启定位权限后再尝试");
      return (ssid: null, password: null);
    }
    final ssid = ssidResult.ssid;
    if (ssid == null) {
      return (ssid: null, password: null);
    }
    final spUnit = await SPUtils.getInstance();
    final pwd = spUnit.getString(ssid);
    if (pwd.isEmpty) {
      return (ssid: null, password: null);
    }
    return (ssid: ssid, password: pwd);
  }

  Future<Map<String, String?>?> _showModalWifiConfig(
    BuildContext context,
  ) async {
    if (context.mounted == false) {
      return null;
    }
    final result = await showModalBottomSheet<Map<String, String?>>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (ctx) {
        final bottom = MediaQuery.of(ctx).padding.bottom;
        return ClipRRect(
          borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
          child: Container(
            color: context.colorScheme.surface,
            padding: EdgeInsets.only(bottom: bottom),
            child: WifiConfigScreen(
              pid: "",
              deviceName: "",
              nextRoute: 'pop',
              isModal: true,
            ),
          ),
        );
      },
    );

    return result;
  }
}
